from django.shortcuts import render, get_object_or_404, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json
import pandas as pd

from .models import Template, TemplateUsageLog


def template_management_index(request):
    """模板管理首页"""
    templates = Template.objects.filter(is_active=True).order_by('-created_at')
    return render(request, 'template_management/template_index.html', {
        'templates': templates
    })


def template_create(request):
    """创建模板"""
    if request.method == 'GET':
        return render(request, 'template_management/template_create.html')
    
    elif request.method == 'POST':
        try:
            # 获取基本信息
            name = request.POST.get('name')
            description = request.POST.get('description', '')
            file_type = request.POST.get('file_type', 'excel')
            output_format = request.POST.get('output_format', 'excel')
            
            # 获取字段配置和处理逻辑
            field_configs = json.loads(request.POST.get('field_configs', '{}'))
            processing_logic = request.POST.get('processing_logic', '{}')
            
            # 创建模板
            template = Template.objects.create(
                name=name,
                description=description,
                file_type=file_type,
                output_format=output_format,
                field_configs=field_configs,
                processing_logic=processing_logic
            )
            
            return JsonResponse({
                'success': True,
                'message': '模板创建成功',
                'template_id': str(template.id)  # 将UUID转换为字符串
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            })


def template_edit(request, template_id):
    """编辑模板"""
    template = get_object_or_404(Template, id=template_id)
    
    if request.method == 'GET':
        # 获取模板的完整配置
        template_data = {
            'id': str(template.id),  # 将UUID转换为字符串
            'name': template.name,
            'description': template.description,
            'file_type': template.file_type,
            'output_format': template.output_format,
            'field_configs': template.field_configs or {},
            'processing_logic': template.processing_logic or '{}'
        }
        
        return render(request, 'template_management/template_edit.html', {
            'template': template,
            'template_data': json.dumps(template_data, ensure_ascii=False),
            'field_configs_json': json.dumps(template.field_configs or {}, ensure_ascii=False)
        })
    
    elif request.method == 'POST':
        try:
            # 更新基本信息
            template.name = request.POST.get('name', template.name)
            template.description = request.POST.get('description', template.description)
            template.file_type = request.POST.get('file_type', template.file_type)
            template.output_format = request.POST.get('output_format', template.output_format)
            
            # 更新字段配置和处理逻辑
            field_configs = json.loads(request.POST.get('field_configs', '{}'))
            processing_logic = request.POST.get('processing_logic', '{}')
            template.field_configs = field_configs
            template.processing_logic = processing_logic
            template.save()
            
            return JsonResponse({
                'success': True,
                'message': '模板更新成功'
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            })


def template_preview(request, template_id):
    """模板预览"""
    template = get_object_or_404(Template, id=template_id)
    
    # 获取模板的详细配置信息
    template_info = {
        'basic_info': {
            'name': template.name,
            'description': template.description,
            'template_type': template.get_template_type_display(),
            'data_source_type': template.get_data_source_type_display(),
            'created_at': template.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': template.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        },
        'data_sources': [
            {
                'source_name': ds.source_name,
                'source_type': ds.get_source_type_display(),
                'read_direction': ds.get_read_direction_display(),
                'data_range': ds.data_range,
                'header_config': ds.header_config,
                'join_keys': ds.join_keys,
                'filter_conditions': ds.filter_conditions
            }
            for ds in template.data_sources.all().order_by('source_order')
        ],
        'processing_rules': [
            {
                'rule_name': rule.rule_name,
                'rule_type': rule.get_rule_type_display(),
                'rule_config': rule.rule_config,
                'condition_config': rule.condition_config,
                'is_active': rule.is_active
            }
            for rule in template.processing_rules.all().order_by('rule_order')
        ],
        'output_configs': [
            {
                'output_name': output.output_name,
                'output_type': output.get_output_type_display(),
                'output_format': output.get_output_format_display(),
                'output_config': output.output_config,
                'filename_template': output.filename_template
            }
            for output in template.output_configs.all()
        ]
    }
    
    return render(request, 'template_management/template_preview.html', {
        'template': template,
        'template_info': template_info
    })


def template_test(request, template_id):
    """模板测试"""
    template = get_object_or_404(Template, id=template_id)
    
    if request.method == 'GET':
        # 获取模板需要的数据源信息
        data_sources_info = [
            {
                'source_name': ds.source_name,
                'source_type': ds.source_type,
                'description': f"{ds.get_source_type_display()} - {ds.get_read_direction_display()}"
            }
            for ds in template.data_sources.all().order_by('source_order')
        ]
        
        return render(request, 'template_management/template_test.html', {
            'template': template,
            'data_sources_info': data_sources_info
        })
    
    elif request.method == 'POST':
        try:
            # 获取上传的文件
            uploaded_files = {}
            for ds in template.data_sources.all():
                file_key = f"file_{ds.source_name}"
                if file_key in request.FILES:
                    uploaded_files[ds.source_name] = request.FILES[file_key]
            
            if not uploaded_files:
                return JsonResponse({
                    'success': False,
                    'error': '请上传至少一个数据文件'
                })
            
            # 简单处理上传的文件
            result = {
                'success': True,
                'message': f'成功上传 {len(uploaded_files)} 个文件'
            }
            
            return JsonResponse(result)
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            })


@csrf_exempt
@require_http_methods(["POST"])
def template_process_data(request):
    """使用模板处理数据"""
    try:
        template_id = request.POST.get('template_id')
        if not template_id:
            return JsonResponse({
                'success': False,
                'error': '请选择模板'
            })
        
        template = get_object_or_404(Template, id=template_id)
        
        # 获取上传的文件
        if 'data_file' not in request.FILES:
            return JsonResponse({
                'success': False,
                'error': '请上传数据文件'
            })
        
        uploaded_file = request.FILES['data_file']
        
        # 读取文件数据
        try:
            if template.file_type == 'excel':
                # 读取Excel文件
                data = pd.read_excel(uploaded_file, sheet_name=None)  # 读取所有工作表
            elif template.file_type == 'csv':
                # 读取CSV文件
                data = pd.read_csv(uploaded_file)
            else:
                return JsonResponse({
                    'success': False,
                    'error': f'不支持的文件类型: {template.file_type}'
                })
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': f'文件读取失败: {str(e)}'
            })
        
        # 简单的数据处理逻辑
        result = {
            'success': True,
            'data': data,
            'message': f'成功读取文件: {uploaded_file.name}'
        }
        
        if result['success']:
            # 记录使用日志
            TemplateUsageLog.objects.create(
                template=template,
                input_file_name=uploaded_file.name,
                input_file_size=uploaded_file.size,
                processing_status='success',
                processing_result=result.get('message', ''),
                output_records_count=len(result['data']) if isinstance(result['data'], pd.DataFrame) else sum(len(df) for df in result['data'].values()) if isinstance(result['data'], dict) else 0
            )
        else:
            # 记录错误日志
            TemplateUsageLog.objects.create(
                template=template,
                input_file_name=uploaded_file.name,
                input_file_size=uploaded_file.size,
                processing_status='error',
                error_message=result.get('error', ''),
                processing_result=result.get('message', '')
            )
        
        return JsonResponse(result)
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        })


def template_delete(request, template_id):
    """删除模板"""
    if request.method == 'POST':
        try:
            template = get_object_or_404(Template, id=template_id)
            template.is_active = False
            template.save()
            
            return JsonResponse({
                'success': True,
                'message': '模板删除成功'
            })
            
        except Exception as e:
            return JsonResponse({
                'success': False,
                'error': str(e)
            })
    
    return JsonResponse({
        'success': False,
        'error': '不支持的请求方法'
    })





def get_template_list(request):
    """获取模板列表API"""
    templates = Template.objects.filter(is_active=True).order_by('-created_at')
    
    template_list = [
        {
            'id': template.id,
            'name': template.name,
            'description': template.description,
            'file_type': template.file_type,
            'output_format': template.output_format,
            'created_at': template.created_at.strftime('%Y-%m-%d %H:%M:%S'),

            'usage_count': template.usage_logs.count()
        }
        for template in templates
    ]
    
    return JsonResponse({
        'success': True,
        'templates': template_list
    })